package com.csti.delio.produccion.client.clientes;

import java.util.ArrayList;
import java.util.List;

import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.binding.FieldBinding;
import com.extjs.gxt.ui.client.binding.FormBinding;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.GridEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.button.ButtonBar;
import com.extjs.gxt.ui.client.widget.form.Field;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.HiddenField;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.Validator;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.filters.GridFilters;
import com.extjs.gxt.ui.client.widget.grid.filters.StringFilter;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.toolbar.PagingToolBar;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;

public class ClienteForm extends ContentPanel{
	Button addCliente;
	ToolBar toolBar;
	ContentPanel cpw;
	BorderLayoutData sup,inf,east,center,gridc,buttons;
	TextField<String> codigo,razonsocial,nombres,nombrecomercial,direccion,telefono,celular,email,rpc,rpm,observacion;
	TextField<String> codigof,razonsocialf,nombresf,nombrecomercialf,direccionf,telefonof,celularf,emailf,rpcf,rpmf,observacionf;
	HiddenField<String> id;
	NumberField ruc,rucf;
	private FormBinding formbinding;
	FormPanel fp,f;
	Dialog dl;

 	public ClienteForm(){
		setHeaderVisible(false);
		BorderLayout layout = new BorderLayout();
		setLayout(layout);
		addForm();	
		formulario();
	 	    
	    cpw = new ContentPanel();
	    cpw.setHeading("Editar Cliente");
	    cpw.setIconStyle("images/icons/people.png");
	    sup = new BorderLayoutData(LayoutRegion.NORTH);
	    sup.setMargins(new Margins(2));
	    
        inf = new BorderLayoutData(LayoutRegion.SOUTH);
        inf.setMargins(new Margins(2));
        fp.setEnabled(false);
	    cpw.add(fp,sup);
	    cpw.add(contPanel(),inf);
	     
	    east = new BorderLayoutData(LayoutRegion.EAST,350);
	    east.setMargins(new Margins(2));
	    east.setSplit(true);
	    east.setCollapsible(true);
	    
	    center  = new BorderLayoutData(LayoutRegion.CENTER);
	    center.setMargins(new Margins(2));
	    center.setCollapsible(true);
	    
	    ContentPanel ctp = new ContentPanel();
	    ctp.setLayout(new BorderLayout());
	    ctp.setHeading("Listado de Clientes");
	    ctp.setIconStyle("images/icons/table.png");
	    
	    gridc   = new BorderLayoutData(LayoutRegion.CENTER);
	    buttons = new BorderLayoutData(LayoutRegion.SOUTH,25);
	    
	    Clientes.getPaginate();
	    
	    final PagingToolBar toolBarPag = new PagingToolBar(10);
        toolBarPag.bind(Clientes.loader);
        
        List<ColumnConfig> conf = new ArrayList<ColumnConfig>();
        CheckBoxSelectionModel<BeanModel> sm = new CheckBoxSelectionModel<BeanModel>();
    
        conf.add(sm.getColumn()); 

        ColumnConfig col  = new ColumnConfig("codigo","Codigo",100);
	    conf.add(col);
	    col  = new ColumnConfig("razonsocial","Razon Social",100);
	    conf.add(col);
	    col  = new ColumnConfig("nombres","Nombres",100);
	    conf.add(col);
	    col  = new ColumnConfig("nombrecomercial","Nombre Comercial",100);
	    conf.add(col);
	    col  = new ColumnConfig("ruc","Ruc",100);
	    conf.add(col);
	    col  = new ColumnConfig("direccion","Direccion",150);
	    conf.add(col);
	    col  = new ColumnConfig("telefono","Telefono",100);
	    conf.add(col);
	    col  = new ColumnConfig("celular","Celular",100);
	    conf.add(col);
	    col  = new ColumnConfig("email","Email",100);
	    conf.add(col);
	    col  = new ColumnConfig("rpc","Rpc",100);
	    conf.add(col);
	    col  = new ColumnConfig("rpm","Rpm",100);
	    conf.add(col);
	    col  = new ColumnConfig("observacion","Observacion",200);
	    conf.add(col);
	    
	    final ColumnModel cm = new ColumnModel(conf);
	    
	    Grid<BeanModel> grid = new Grid<BeanModel>(Clientes.store, cm);  
        grid.addListener(Events.Attach, new Listener<GridEvent<BeanModel>>() {  
          public void handleEvent(GridEvent<BeanModel> be) {  
        	  Clientes.loader.load(0, 10);  
          }  
        }); 
        
        grid.setSelectionModel(sm);
        grid.getSelectionModel().addListener(Events.SelectionChange,
           new Listener<SelectionChangedEvent<BeanModel>>() {
			@Override
			public void handleEvent(SelectionChangedEvent<BeanModel> be) {		
    			if (be.getSelection().size() > 0) {
	            	  formbinding.bind((BeanModel) be.getSelection().get(0));  
	            	  fp.setEnabled(true);
		        } else {  
		              formbinding.unbind();  
		        }
			}
        	
        });
        
        grid.setLoadMask(true);  
        grid.setBorders(true);       
         	
        toolBar = new ToolBar(); 
        addCliente = new Button("Agregar", IconHelper.createPath("images/icons/new.gif"));
        
        GridFilters filters = new GridFilters();
        StringFilter codigoFilter = new StringFilter("codigo");        
        StringFilter razonsocialFilter = new StringFilter("razonsocial");
        StringFilter nombresFilter = new StringFilter("nombres");
        StringFilter nombrecomercialFilter = new StringFilter("nombrecomercial");
        StringFilter rucFilter = new StringFilter("ruc");
        StringFilter direccionFilter = new StringFilter("direccion");
        StringFilter telefonoFilter = new StringFilter("telefono");
        StringFilter celularFilter = new StringFilter("celular");
        StringFilter emailFilter = new StringFilter("email");
        StringFilter rpcFilter = new StringFilter("rpc");
        StringFilter rpmFilter = new StringFilter("rpm");
        StringFilter observacionFilter = new StringFilter("observacion");

          
        filters.addFilter(codigoFilter);        
        filters.addFilter(razonsocialFilter);        
        filters.addFilter(nombresFilter);        
        filters.addFilter(nombrecomercialFilter);
        filters.addFilter(rucFilter);
        filters.addFilter(direccionFilter);
        filters.addFilter(telefonoFilter);
        filters.addFilter(celularFilter);
        filters.addFilter(emailFilter);
        filters.addFilter(rpcFilter);
        filters.addFilter(rpmFilter);
        filters.addFilter(observacionFilter);
         
        grid.addPlugin(filters);                
        grid.addPlugin(sm);
        formbinding = new FormBinding(fp);
       // codigo,razonsocial,nombres,nombrecomercial,direccion,telefono,celular,email,rpc,rpm,observacion
        formbinding.setStore(Clientes.store);
	    formbinding.addFieldBinding(new FieldBinding(id,"id"));
	    formbinding.addFieldBinding(new FieldBinding(codigo,"codigo"));
	    formbinding.addFieldBinding(new FieldBinding(razonsocial,"razonsocial"));
	    formbinding.addFieldBinding(new FieldBinding(nombres,"nombres"));
	    formbinding.addFieldBinding(new FieldBinding(nombrecomercial,"nombrecomercial"));
	    formbinding.addFieldBinding(new FieldBinding(ruc,"ruc"));
	    formbinding.addFieldBinding(new FieldBinding(direccion,"direccion"));
	    formbinding.addFieldBinding(new FieldBinding(telefono,"telefono"));
	    formbinding.addFieldBinding(new FieldBinding(celular,"celular"));
	    formbinding.addFieldBinding(new FieldBinding(email,"email"));
	    formbinding.addFieldBinding(new FieldBinding(rpc,"rpc"));
	    formbinding.addFieldBinding(new FieldBinding(rpm,"rpm"));
	    formbinding.addFieldBinding(new FieldBinding(observacion,"observacion"));
	    
		ctp.setTopComponent(bbutonbar());    
	    ctp.add(grid,gridc);
	    ctp.add(toolBarPag,buttons);
	     
	    add(ctp,center);
	    add(cpw,east);
	}
	
    public ContentPanel contPanel(){
		   ContentPanel cp  = new ContentPanel();
		   return cp;
	 }
	 
	 
	 public ButtonBar bbutonbar(){
		   dl = new Dialog();  
		   dl.setBodyBorder(false);  
		   dl.setHeading("Nuevo Cliente");  
		   dl.setWidth(330);  
		   dl.setHeight(335); 
		   dl.setClosable(true);
		   dl.setIconStyle("images/icons/new.gif");
		   dl.setModal(true);
			   
		   Button salir  = new Button("Salir",IconHelper.create("images/icons/exit.png"));
		   Button guardar = new Button("Guardar",IconHelper.create("images/icons/save_all.png"));
		  
		   dl.setButtons("");
		   dl.addButton(salir);
		   dl.addButton(guardar);


		   
		   salir.addSelectionListener(new SelectionListener<ButtonEvent>(){
			  public void componentSelected(ButtonEvent ce){
				  dl.hide();
			  }
		   });
		   guardar.addSelectionListener(new SelectionListener<ButtonEvent>(){
			   public void componentSelected(ButtonEvent ve){
				   if(validate()){
				     Cliente c = new Cliente();
				     c.setCodigo(codigof.getValue());
				     c.setRazonsocial(razonsocialf.getValue());
				     c.setNombres(nombresf.getValue());
				     c.setNombrecomercial(nombrecomercialf.getValue());
				     c.setRuc(rucf.getValue().longValue());
				     c.setDireccion(direccionf.getValue());
				     c.setTelefono(telefonof.getValue());
				     c.setCelular(celularf.getValue());
				     c.setEmail(emailf.getValue());
				     c.setRpc(rpcf.getValue());
				     c.setRpm(rpmf.getValue());
				     c.setObservacion(observacionf.getValue());
				     Clientes.guardar(c);
				     Clientes.cf = ClienteForm.this;
				     Clientes.loader.load();
			     }
			   }
		   });
		 		 	  
		  ButtonBar bb = new ButtonBar();
		  Button btnNew = new Button("Nuevo",IconHelper.createPath("images/icons/new.gif"));
		  Button btnUpdate = new Button("Actualizar",IconHelper.createPath("images/icons/update.png"));
		  Button btnEliminar = new Button("Eliminar",IconHelper.createPath("images/icons/delete.gif"));
		  bb.add(btnNew);
		  bb.add(btnUpdate);
		  bb.add(btnEliminar);
		  
		  btnNew.addSelectionListener(new SelectionListener<ButtonEvent>() {
		      public void componentSelected(ButtonEvent ce) {
		          dl.add(f);
		          dl.show(); 
			      }
		    });
		  
		  btnUpdate.addSelectionListener(new SelectionListener<ButtonEvent>(){
			  public void componentSelected(ButtonEvent be){
				if(id.getValue() != null){
				   Listener<MessageBoxEvent> callback = new Listener<MessageBoxEvent>() {	 
					 public void handleEvent(MessageBoxEvent be) {
					   if(be.getButtonClicked().getItemId().equals(Dialog.YES)) {  
					     Cliente cl = new Cliente();
					     cl.setId(Integer.parseInt(id.getValue()));
					     cl.setCodigo(codigo.getValue());
					     cl.setRazonsocial(razonsocial.getValue());
					     cl.setNombres(nombres.getValue());
					     cl.setNombrecomercial(nombrecomercial.getValue());
					     cl.setRuc(ruc.getValue().longValue());
						 cl.setDireccion(direccion.getValue()); 
						 cl.setTelefono(telefono.getValue());
						 cl.setCelular(celular.getValue());
						 cl.setEmail(email.getValue());
						 cl.setRpc(rpc.getValue());
						 cl.setRpm(rpm.getValue());
						 cl.setObservacion(observacion.getValue());
						 Clientes.actualizar(cl);
						 Clientes.loader.load();
					   }
					 }
			      };
			      String msg = "Esta seguro que desea Actualizar el Cliente?";
			      MessageBox.confirm("Actualizar Cliente?", msg, callback);
			 	}else{
				  MessageBox.alert("Seleccionar", "Seleccione una fila porfavor", null);
			    }
			  }
		  });
		  
		  btnEliminar.addSelectionListener(new SelectionListener<ButtonEvent>(){
			 public void componentSelected(ButtonEvent ce){
			  if(id.getValue() != null){	 
			    Listener<MessageBoxEvent> callback = new Listener<MessageBoxEvent>() {	 
				  public void handleEvent(MessageBoxEvent be) {
		           if (be.getButtonClicked().getItemId().equals(Dialog.YES)) { 
				        Clientes.eliminar(Integer.parseInt(id.getValue()));
					    Clientes.loader.load();
			         }
		            }
			      };
			       String msg = "Esta seguro que desea eliminar al Cliente?";
			       MessageBox.confirm("Eliminar Cliente?", msg, callback);
			 	  }else{
				   MessageBox.alert("Seleccionar", "Seleccione una fila porfavor", null);
			      }
			    }
		     });
		  return bb;
	  }
	 
	public boolean validate(){
	   boolean cd  = codigo.isValid();
	   boolean rs  = razonsocialf.isValid();
	   boolean nom = nombresf.isValid();
	   boolean nc  = nombrecomercialf.isValid();
	   boolean ruc = rucf.isValid();
	   boolean d   = direccionf.isValid();
	   boolean t   = telefonof.isValid();
	   boolean cel = celularf.isValid();
	   boolean eml = emailf.isValid();
	   boolean rc  = rpcf.isValid();
	   boolean rm  = rpmf.isValid();
	   boolean ob  = observacionf.isValid();
	   
	  return cd&&rs&&nom&&nc&&ruc&&d&&t&&cel&&eml&&rc&&rm&&ob;
	}
	 
			  
	public void addForm(){
		fp = new FormPanel();
		fp.setHeaderVisible(false);
		fp.setFrame(true);
		id = new HiddenField<String>();
		id.setVisible(false);
		codigo = new TextField<String>();
		codigo.setFieldLabel("Codigo");
		codigo.setAllowBlank(true);
		razonsocial = new TextField<String>();
		razonsocial.setFieldLabel("Razon Social");
		razonsocial.setAllowBlank(true);
		razonsocial.getSelectOnFocus();
		nombres.setFieldLabel("Nombres");
		nombres.getSelectOnFocus();
		nombrecomercial.setFieldLabel("Nombre Comercial");
		nombrecomercial.getSelectOnFocus();
		ruc = new NumberField();
		ruc.setPropertyEditorType(Long.class);
		ruc.setFieldLabel("Ruc");
		ruc.setMaxLength(11);
		ruc.setMinLength(11);
		ruc.setAllowBlank(true);
    	direccion = new TextField<String>();
		direccion.setFieldLabel("Direccion");
		telefono = new TextField<String>();
		telefono.setFieldLabel("Telefono");
		celular = new TextField<String>();
		celular.setFieldLabel("Celular");
		email = new TextField<String>();
		email.setFieldLabel("Email");
		final String emailReg = "[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}";
	    final String errMsg = "Not a valid email address!";
	    email.setValidator(new Validator() {
	      public String validate(Field<?> field, String value) {
	        if (!value.toUpperCase().matches(emailReg))
	          return errMsg;
	        return null;
	      }
	    });
		rpc = new TextField<String>();
		rpc.setFieldLabel("Rpc");
		rpm = new TextField<String>();
		rpm.setFieldLabel("Rpm");
		observacion = new TextField<String>();
		observacion.setFieldLabel("Observacion");  
		fp.add(id);
		fp.add(codigo);
		fp.add(razonsocial);
		fp.add(nombres);
		fp.add(nombrecomercial);
		fp.add(ruc);
		fp.add(direccion); 		
        fp.add(telefono);
        fp.add(celular);
        fp.add(email);
        fp.add(rpc);
        fp.add(rpm);
        fp.add(observacion);
  	}
	
   public void formulario(){
		f = new FormPanel();
		f.setHeaderVisible(false);
		codigof = new TextField<String>();
		codigof.setAllowBlank(false);
		codigof.setFieldLabel("Codigo");
		razonsocialf = new TextField<String>();
		razonsocialf.setAllowBlank(false);
		razonsocialf.setFieldLabel("Razon Social");
		razonsocialf.getSelectOnFocus();
		nombresf = new TextField<String>();
		nombresf.setAllowBlank(false);
		nombresf.setFieldLabel("Nombres");
		nombrecomercialf = new TextField<String>();
		nombrecomercialf.setAllowBlank(false);
		nombrecomercialf.setFieldLabel("Nombre Comercial");
		rucf = new NumberField();
		rucf.setMinLength(8);
		rucf.setMaxLength(11);
		rucf.setAllowBlank(false);
		rucf.setPropertyEditorType(Long.class);
		rucf.setFieldLabel("Ruc");
		direccionf = new TextField<String>();
		direccionf.setFieldLabel("Direccion");
		telefonof = new TextField<String>();
		telefonof.setFieldLabel("Telefono");
		celularf = new TextField<String>();
		celularf.setFieldLabel("Celular");
		emailf = new TextField<String>();
		emailf.setFieldLabel("Email");
		final String emailReg = "[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}";
	    final String errMsg = "Not a valid email address!";
	    emailf.setValidator(new Validator() {
	      public String validate(Field<?> field, String value) {
	        if (!value.toUpperCase().matches(emailReg))
	          return errMsg;
	        return null;
	      }
	    });
	   	rpcf = new TextField<String>();
		rpcf.setFieldLabel("Rpc");
		rpmf = new TextField<String>();
		rpmf.setFieldLabel("Rpm");
		observacionf = new TextField<String>();
		observacionf.setFieldLabel("Observacion");
		f.add(codigof,new FormData("-20"));
		f.add(razonsocialf,new FormData("-20"));
		f.add(nombresf,new FormData("-20"));
		f.add(nombrecomercialf,new FormData("-20"));
		f.add(rucf,new FormData("-20"));
        f.add(direccionf,new FormData("-20")); 		
        f.add(telefonof,new FormData("-20"));
        f.add(celularf,new FormData("-20"));
        f.add(emailf,new FormData("-20"));
        f.add(rpcf,new FormData("-20"));
        f.add(rpmf,new FormData("-20"));
        f.add(observacionf,new FormData("-20"));
   }
   
   public void clearForm(){
	   codigof.clear();
	   razonsocialf.clear();
	   nombresf.clear();
	   nombrecomercialf.clear();
	   rucf.clear();
	   direccionf.clear();
	   telefonof.clear();
	   celularf.clear();
	   emailf.clear();
	   rpcf.clear();
	   rpmf.clear();
	   observacionf.clear();
   }
   
}